import React, { useEffect } from 'react';
import { useState } from 'react';
import api from './api/api';
import { ToastContainer, Toast } from 'react-bootstrap';
import EditDescription from './EditDescription';
import { useHistory, useParams } from 'react-router-dom/cjs/react-router-dom';

const EditPodcast = () => {
  const { id } = useParams();
  const history = useHistory();
  const [isLoading, setIsLoading] = useState(true);
  const [podcast, setPodcast] = useState({});
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [category, setCategory] = useState('');
  const [cover, setCover] = useState('');
  const [toastShow, setToastShow] = useState(false);
  const [toastContent, setToastContent] = useState('');

  const handleSubmit = async () => {
    const body = {};
    if (title)
      body.title = title;
    if (description)
      body.description = description;
    if (category)
      body.itunes_category = category;
    try {
      const response = await api.put(`/podcasts/${id}`, body);
      if (cover) {
        const formData = new FormData();
        formData.append('avatar_update', cover);
        const coverUploadResponse = await api.put(`podcasts/${podcast.id}/cover`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
      }
      setToastContent("修改成功！");
      setTimeout(() => {
        history.push(`/podcasts/${id}`);
      }, 2000);
    } catch (error) {
      setToastContent(`修改失败：${error.message}`);
    } finally {
      setToastShow(true);
      setTimeout(() => {
        setToastShow(false);
      }, 2000);
    }
  };

  useEffect(() => {
    const getPodcast = async () => {
      try {
        const response = await api.get(`/podcasts/${id}`);
        const returnedPodcast = response.data;
        setPodcast(returnedPodcast);
        setDescription(returnedPodcast.description);
        setIsLoading(false);
      } catch (error) {
        console.log(error);
      }
    };
    getPodcast();
  }, [id]);

  return (
    <div className='
        container
        min-h-100
        flex-fill'
    >
      <div className="container d-flex flex-column align-items-center">
        <h1 className='mt-2 mb-5'>编辑播客</h1>
        {!isLoading &&
          <form className='mb-2' onSubmit={(e) => e.preventDefault()}>
            <div className="mb-3">
              <label for="title" className="form-label">专辑名称</label>
              <input type="text" className="form-control" id="title" placeholder={podcast.title} onChange={(e) => setTitle(e.target.value)} />
            </div>
            <div className="mb-3">
              <label for="category" className="form-label">分类</label>
              <input type="text" className="form-control" id="category" placeholder={podcast.itunes_category} onChange={(e) => setCategory(e.target.value)} />
              <div className="form-text">建议您参考<a href="https://podcasters.apple.com/support/1691-apple-podcasts-categories" target='_blank' rel='noreferrer'> Apple Podcast 分类文档</a>填写。</div>

            </div>
            <div className='mb-3'>
              <label for="description" className="form-label">描述</label>
              <EditDescription description={description} setDescription={setDescription} />
            </div>
            <div className="mb-3">
              <label for="avatar" className="form-label">封面</label>
              <input type="file" accept='image/*' className="form-control" id="avatar" onChange={(e) => setCover(e.target.files[0])} />
              <div className="form-text">请选择正方形尺寸图片。</div>
            </div>
            <div className="text-center mb-4">
              <button type="submit" className="btn btn-primary" onClick={handleSubmit}>提交</button>
            </div>
          </form>
        }
      </div>
      <ToastContainer position='middle-center' className='m-2'>
        <Toast show={toastShow} onClose={() => { setToastShow(false); }}>
          <Toast.Header>
            <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" />
            <strong className="me-auto">雨呓</strong>
          </Toast.Header>
          <Toast.Body>{toastContent}</Toast.Body>
        </Toast>
      </ToastContainer>
    </div>
  );
};

export default EditPodcast;
